package com.ledim.utils;

import android.media.AudioManager;
import android.media.MediaPlayer;
import java.io.IOException;

/**
 * Created by ccx on 16/6/29.
 */
public class LedimRecordPlayer
        implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener,
                   MediaPlayer.OnPreparedListener {

    public MediaPlayer mediaPlayer;
    private LedimRecordPlayerState state;

    public LedimRecordPlayer() {
        initVedio();

    }

    public LedimRecordPlayer(LedimRecordPlayerState state) {
        this.state = state;
        initVedio();
    }

    private void initVedio() {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            LogUtil.e("mediaPlayer", "error==" + e.getMessage());
        }
    }

    public void play() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
        }
    }

    public void playUrl(String videoUrl) {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
        }

        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(videoUrl);
            mediaPlayer.prepare();//prepare之后自动播放
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void pause() {
        mediaPlayer.pause();
    }

    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
            if (state != null) {
                state.onStop();
            }
        }
    }

    @Override
    /**
     * 通过onPrepared播放
     */ public void onPrepared(MediaPlayer arg0) {
        if (state != null) {
            state.onStart();
        }
        arg0.start();
        LogUtil.e("mediaPlayer", "onPrepared");
    }

    @Override
    public void onCompletion(MediaPlayer arg0) {
        LogUtil.e("mediaPlayer", "onCompletion");
        if (state != null) {
            state.onComplete();
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
    }

    public interface LedimRecordPlayerState {

        void onStart();

        void onComplete();

        void onStop();
    }
}
